package com.magic.himalaya.views;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

import com.magic.himalaya.R;

/**
 * @description:
 * @create: Create by Magic on 2022/1/21.
 */
public class LoadingView extends androidx.appcompat.widget.AppCompatImageView {
    private static final String TAG = LoadingView.class.getSimpleName();

    private int rotateDegree = 0;//旋转角度
    private boolean mNeedRotate = false;

    public LoadingView(Context context) {
        this(context,null);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setImageResource(R.drawable.ic_loading);//设置图标
    }

    /**
     * 绑定到window
     */
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        //绑定
        mNeedRotate = true;
        //post()代表执行一个线程内容
        post(() -> {
           rotateDegree+=5;
           rotateDegree = rotateDegree<=360?rotateDegree:0;
           invalidate();//更新View,重新渲染
           if (mNeedRotate) {
               postDelayed(this::onAttachedToWindow, 40);
           }
        });
    }

    /**
     * 解绑window
     */
    @Override
    protected void onDetachedFromWindow() {
        //解绑
        mNeedRotate = false;
        super.onDetachedFromWindow();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //参数: 旋转角度,旋转的x坐标,旋转的y坐标
        canvas.rotate(rotateDegree,getWidth()/2,getHeight()/2);
        super.onDraw(canvas);

    }
}
